package com.education.welco.controller.teacherapp;

import com.alibaba.fastjson.JSONObject;
import com.education.common.pojo.AjaxResult;
import com.education.utils.JwtUtil;
import com.education.websocket.data.HomeBuffer;
import com.education.websocket.data.HomeData;
import com.education.websocket.server.WebSocketServerWELCO;
import com.education.welco.pojo.OrderAnswer;
import com.education.welco.pojo.OrderPaper;
import com.education.welco.pojo.OrderUserPaper;
import com.education.welco.pojo.vo.*;
import com.education.welco.service.ITStudentService;
import com.education.welco.service.OrderAnswerService;
import com.education.welco.service.OrderPaperService;
import com.education.welco.service.OrderUserPaperService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: liftsail
 * @Date: 2023/1/17 14:00
 * @Description: 不积跬步无以至千里
 */
@RestController
@RequestMapping("/apptea/correctPapers")
public class AppTeaCorrectPapersController {

    @Autowired
    private OrderPaperService orderPaperService;
    @Autowired
    private OrderAnswerService orderAnswerService;
    @Autowired
    private OrderUserPaperService orderUserPaperService;
    @Autowired
    private ITStudentService studentService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HomeBuffer homeBuffer;

    /**
     * 批改试卷列表
     *
     * @param teaId    老师用户id
     * @param pageNum  分页参数
     * @param pageSize 分页参数
     * @return 批改试卷列表
     */
    @GetMapping("/paperListByTeacher")
    public AjaxResult paperListByTeacher(@RequestParam(value = "teaId", required = false) Integer teaId,
                                         @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                         @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<OrderPaperAppVO> paperList = orderPaperService.selectPaperListForTea(teaId);
        return AjaxResult.success(new PageInfo<>(paperList));
    }

    /**
     * 试卷整体批改详情  根据试卷id
     *
     * @param teaId     老师id
     * @param paperId   试卷id
     * @param catalogId 课程id
     * @param likeName  模糊匹配
     * @param pageNum   分页
     * @param pageSize  分页
     * @return 作业整体批改详情
     */
    @GetMapping("/wholePaperInfo")
    public AjaxResult wholePaperInfo(@RequestParam(value = "teaId", required = false) Integer teaId,
                                     @RequestParam(value = "paperId", required = false) Integer paperId,
                                     @RequestParam(value = "catalogId", required = false) Integer catalogId,
                                     @RequestParam(value = "likeName", required = false) String likeName,
                                     @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                     @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        //1.试卷详情列表
        List<WholePaperInfoAppVO> workList = orderUserPaperService.wholePaperInfo(paperId, likeName);
        map.put("list", workList);
        //2.平均分(已批阅的总分/已批阅学生总数)
        List<WholePaperInfoAppVO> workListAll = orderUserPaperService.wholePaperInfo(paperId, null);
        workListAll = workListAll.parallelStream().filter(a -> a.getPaperState().equals("1")).collect(Collectors.toList());
        BigDecimal ave = new BigDecimal(0);
        if (workListAll.size() > 0) {
            ave = (workListAll.stream().map(WholePaperInfoAppVO::getTeaScore).reduce(BigDecimal.ZERO, BigDecimal::add)).divide(new BigDecimal(workListAll.size()), 2, 3);
        }
        map.put("average", ave);
        //3.最高分、最低分  排序
        workListAll = workListAll.parallelStream().sorted(Comparator.comparing(a -> a.getTeaScore())).collect(Collectors.toList());//正序
        if (workListAll.size() == 0) {
            map.put("low", new WholePaperInfoAppVO());
            map.put("high", new WholePaperInfoAppVO());
        } else {
            WholePaperInfoAppVO wholePaperInfoAppVO = workListAll.get(0);//最低分
            map.put("low", wholePaperInfoAppVO);
            WholePaperInfoAppVO wholePaperInfoAppVO1 = workListAll.get(workListAll.size() - 1);//最高分
            map.put("high", wholePaperInfoAppVO1);
        }
        return AjaxResult.success(map);
    }

    /**
     * 批改作业详情 根据学生作业id查找
     *
     * @param stuPaperId
     * @return
     */
    @GetMapping("/stuPaperInfo")
    public AjaxResult stuPaperInfo(@RequestParam(value = "stuPaperId") Integer stuPaperId) {
        OrderUserPaper orderUserPaperpo = orderUserPaperService.selectorderUserPaperById(stuPaperId);
        Integer paperId = orderUserPaperpo.getPaperId();
        Integer userId = Integer.valueOf(orderUserPaperpo.getUserId());
        Map<String, Object> resultMap = new HashMap<>();
        //查找试卷信息
        OrderPaper orderPaper = orderPaperService.selectOrderPaperById(paperId);
        Map<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("singleScore", orderPaper.getSingleScore());
        stringStringHashMap.put("manyScore", orderPaper.getManyScore());
        stringStringHashMap.put("judgmentScore", orderPaper.getJudgmentScore());
        stringStringHashMap.put("answSore", orderPaper.getAnswSore());
        //查找试题列表
        List<ReadQuestionsVo> ReadQuestionsVoList = orderAnswerService.selectQuestionParsing2(paperId, userId);
        ReadQuestionsVoList = ReadQuestionsVoList.stream().filter(readQuestionsVo -> readQuestionsVo.getQuestionType().equals(4)).collect(Collectors.toList());
        //查找老师评语、试卷得分、试卷名称、试卷答题详情
        OrderUserPaper orderUserPaper = orderUserPaperService.SelectOrderUserPaper(paperId, userId);
        //解析试卷详情
        String userPaperInfo = orderUserPaper.getUserPaperInfo();
        UserPaperAnswerInfo userPaperAnswerInfo = JSONObject.parseObject(userPaperInfo, UserPaperAnswerInfo.class);
        resultMap.put("questionList", ReadQuestionsVoList);
        //resultMap.put("paperName", orderUserPaper.getPaperName());
        resultMap.put("paperId", orderUserPaper.getPaperId());
        resultMap.put("paperState", orderUserPaper.getType());
        resultMap.put("questionTypeScore", stringStringHashMap);//题型分值
        resultMap.put("stuId", orderUserPaper.getUserId());//学生id
        resultMap.put("paperComment", "");
        if (StringUtils.isNotBlank(orderUserPaper.getComment())) {
            resultMap.put("paperComment", orderUserPaper.getComment());
        }
        //app定制userPaperAnswerInfo
        userPaperAnswerInfo.setTotalError(userPaperAnswerInfo.getErrordanxuan() + userPaperAnswerInfo.getErrorduoxuan() + userPaperAnswerInfo.getErrorpanduan());
        Integer allNum = userPaperAnswerInfo.getAllNum() - ReadQuestionsVoList.size();
        userPaperAnswerInfo.setTotalNotAns(allNum - userPaperAnswerInfo.getTotalCorrect() - userPaperAnswerInfo.getTotalError());
        resultMap.put("paperDetails", userPaperAnswerInfo);
        return AjaxResult.success(resultMap);
    }

    /**
     * 试卷批改接口
     *
     * @param paperScoreComment json字符串
     * @return
     */
    @PostMapping("/paperMarkById")
    public AjaxResult paperScoreComment(String paperScoreComment) {
        PaperScoreCommentVo paperScoreCommentVo = JSONObject.parseObject(paperScoreComment, PaperScoreCommentVo.class);
        //判断答卷是否批阅
        OrderUserPaper judgeResult = orderUserPaperService.SelectOrderUserPaper(paperScoreCommentVo.getPaperId(), paperScoreCommentVo.getUserId());
        if ("1".equals(judgeResult.getType())) {
            return AjaxResult.success("该试卷已完成批阅");
        }
        //老师用户id
        Integer teaUserId = paperScoreCommentVo.getTeaUserId();
        //判断试卷是否已经批阅
        List<ReadQuestionsVo> questionScoreAns = paperScoreCommentVo.getQuestionScoreAns();
        //更新表数据 1.试题回答2.试卷回答
        //1.orderanswer
        if (!Objects.isNull(questionScoreAns) && questionScoreAns.size() > 0) {
            for (ReadQuestionsVo readQuestionsVo : questionScoreAns) {
                //批量更新记录
                OrderAnswer orderAnswer = new OrderAnswer();
                orderAnswer.setQuestionId(readQuestionsVo.getId());
                orderAnswer.setPaperId(paperScoreCommentVo.getPaperId());
                orderAnswer.setUserId(paperScoreCommentVo.getUserId());
                orderAnswer.setScore(readQuestionsVo.getScore());
                orderAnswerService.updateOrderAnswer1(orderAnswer);
            }
        }
        //2.orderUserPaper
        //累加简答题的分数
        int allAns = 0;
        if (!Objects.isNull(questionScoreAns) && questionScoreAns.size() > 0) {
            for (ReadQuestionsVo questionScoreAn : questionScoreAns) {
                allAns += questionScoreAn.getScore();
            }
        }
        OrderUserPaper orderUserPaper = new OrderUserPaper();
        orderUserPaper.setPaperId(paperScoreCommentVo.getPaperId());
        orderUserPaper.setUserId(String.valueOf(paperScoreCommentVo.getUserId()));
        //sql语句叠加分数
        orderUserPaper.setScore(String.valueOf(allAns));
        orderUserPaper.setComment(paperScoreCommentVo.getComment());
        orderUserPaper.setType(1);
        ////分数累加
        int update = orderUserPaperService.update2(orderUserPaper);
        //websocket数据更新-首页待批试卷数量减1
        //UserInfo userInfo = jwtUtil.getInfoFromToken();
        //Long teaUserId = userInfo.getId();
        Object res = redisTemplate.opsForValue().get("wait:data:" + teaUserId);
        if (Objects.nonNull(res)) {
            HomeData homeData = (HomeData) res;
            if (homeData.getPaperWait() > 0) {
                homeData.setPaperWait(homeData.getPaperWait() - 1);
            }
            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
            WebSocketServerWELCO.sendInfo(homeData, String.valueOf(teaUserId));
        } else {
            //数据初始化
            Object data = homeBuffer.data(String.valueOf(teaUserId));
            HomeData homeData = (HomeData) data;
            if (homeData.getPaperWait() > 0) {
                homeData.setPaperWait(homeData.getPaperWait() - 1);
            }
            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
            WebSocketServerWELCO.sendInfo(homeData, String.valueOf(teaUserId));
        }
        return AjaxResult.success("批改成功");
    }

}
